const Mock = require("mockjs");
const studentsData = require("./studentsData");

// 模拟获取学生列表
Mock.mock("/api/getStudents", "post", (req) => {
  const {
    pageIndex,
    pageSize,
    searchName = "",
    searchAge = "",
    searchGrade = "",
    searchPhoneNumber = "",
  } = JSON.parse(req.body);
  let filterData = studentsData.filter(
    (item) =>
      String(item.age).includes(searchAge) &&
      item.name.includes(searchName) &&
      String(item.grade).includes(searchGrade) &&
      String(item.phoneNumber).includes(searchPhoneNumber)
  );
  return {
    data: filterData.slice(
      (pageIndex - 1) * pageSize,
      Math.min(filterData.length, pageIndex * pageSize)
    ),
    total: filterData.length,
  };
});

// 模拟新增学生
Mock.mock("/api/add", "post", (req) => {
  const { name, age, grade, phoneNumber } = JSON.parse(req.body);
  const newStudent = {
    id: studentsData.length + 1,
    name,
    age,
    grade,
    phoneNumber,
  };
  studentsData.unshift(newStudent);
  return newStudent;
});

// 模拟编辑学生
Mock.mock("/api/update", "post", (req) => {
  const { id, name, age, grade, phoneNumber } = JSON.parse(req.body);
  const index = studentsData.findIndex((student) => student.id === Number(id));
  if (index !== -1) {
    studentsData[index] = {
      ...studentsData[index],
      name,
      age,
      grade,
      phoneNumber,
    };
    return studentsData[index];
  }
  return { error: "学生信息未找到" };
});

// 模拟删除学生
Mock.mock("/api/del", "post", (req) => {
  const { id } = JSON.parse(req.body);
  const index = studentsData.findIndex((student) => student.id === Number(id));
  if (index !== -1) {
    studentsData.splice(index, 1);
    return { success: true };
  }
  return { error: "学生信息未找到" };
});

// 模拟查询学生详情
Mock.mock("/api/getDetail", "post", (req) => {
  const { id } = JSON.parse(req.body);
  const index = studentsData.findIndex((student) => student.id === Number(id));
  if (index !== -1) {
    return studentsData[index];
  }
  return { error: "学生信息未找到" };
});
